﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aoxuelf.MDSTool.Model;

namespace Aoxuelf.MDSTool.SQL
{
    public class DALUpdateMethodWriter : MethodWriter
    {
        public DALUpdateMethodWriter(DALUpdateMethodInfo methodWriteInfo)
            : base(methodWriteInfo)
        {
        }

        private bool IsConcurrency
        {
            get { return ((DALUpdateMethodInfo)methodWriteInfo).IsConcurrency; }
        }

        protected override void WriteSQLParams()
        {
            if (methodWriteInfo.IsTransaction)
            {
                WriteSQLParam(SQLParamInfo.DBTran);
            }
            base.WriteSQLParams();
        }

        protected override void WriteMethodSig()
        {
            string format_Tran = "public int {0}(DbTransaction tran, IDictionary<string, string> dicParam)";
            string format = "public int {0}(IDictionary<string, string> dicParam)";

            if (methodWriteInfo.IsTransaction)
            {
                builder.AppendLine(string.Format(format_Tran, methodWriteInfo.MethodName));
            }
            else
            {
                builder.AppendLine(string.Format(format, methodWriteInfo.MethodName));
            }
        }

        protected override void WriteMethodBody()
        {
            builder.AppendLine("string sqlPath = \"\";");

            if (methodWriteInfo.IsTransaction)
            {
                builder.AppendLine("int affectedRows = DBHelper.UpdateDataInfo(dicParam, sqlPath, tran);");
            }
            else
            {
                builder.AppendLine("int affectedRows = DBHelper.UpdateDataInfo(dicParam, sqlPath);");
            }

            if (IsConcurrency)
            {
                builder.AppendLine();
                builder.AppendLine("//并发校验，如果并发则抛出异常");
                builder.AppendLine("if (affectedRows <= 0)");
                builder.AppendLine("{");
                builder.AppendLine("    throw new ConcurrencyException();");
                builder.AppendLine("}");
                builder.AppendLine();
            }

            builder.AppendLine("return affectedRows;");
        }

        protected override void WriteReturnBody()
        {
            WriteContent("affectedRows", "返回影响的行数", "int");
        }
    }
}
